package lime.dql.dialog;

import lime.Activator;
import lime.dql.widget.FileChooser;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class ExportXmlDialog extends TitleAreaDialog {

	// Widgets
	FileChooser fileChooser;

	private String filePath;

	public ExportXmlDialog(Shell parentShell) {
		super(parentShell);
	}

	@Override
	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setTitle("Export XML");
		setMessage("Please provide the export settings.");
		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite area = (Composite) super.createDialogArea(parent);

		Composite container = new Composite(area, SWT.NULL);
		container.setLayout(new GridLayout(2, false));
		container.setLayoutData(new GridData(GridData.FILL_BOTH));

		// Read previously entered settings
		IDialogSettings loginSettings = getExportXmlSettings();
		String filePathSetting = loginSettings.get("file-path");

		Label fileLabel = new Label(container, SWT.NONE);
		fileLabel.setText("File:");
		fileChooser = new FileChooser(container, SWT.NONE, StringUtils.defaultString(filePathSetting));
		fileChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		return area;
	}

	@Override
	protected Point getInitialSize() {
		return new Point(600, 400);
	}

	@Override
	protected void okPressed() {
		filePath = fileChooser.getFilePath();

		IDialogSettings loginSettings = getExportXmlSettings();
		loginSettings.put("file-path", filePath);

		super.okPressed();
	}

	public String getFilePath() {
		return filePath;
	}

	/**
	 * Retrieve the section from dialog settings that contains the settings for
	 * the export XMLxport XML dialog.
	 */
	private IDialogSettings getExportXmlSettings() {
		IDialogSettings settings = Activator.getDefault().getDialogSettings().getSection("export-xml");
		if (settings == null) {
			settings = Activator.getDefault().getDialogSettings().addNewSection("export-xml");
		}
		return settings;
	}

}
